package com.devshephard.jucks.ForkJoin;

import java.util.concurrent.RecursiveTask;

//forkJoin任务类必须继承RecursiveTask这个父类
public class ForkJoinDemo extends RecursiveTask<Long> {

    private Long start;
    private Long end;

    //临界值
    private Long temp = 10000L;

    public ForkJoinDemo(Long start, Long end) {
        this.start = start;
        this.end = end;
    }


    /**
     * 实现计算
     * @return
     */
    @Override
    protected Long compute() {
        if((end - start) < temp){
            Long sum = 0L;
            for (Long i = start; i <= end; i++) {
                sum += i;
            }
            return sum;
        }else{ //forkJoin

            long middle = (start + end) / 2; //中间值，这里使用了递归思想，每一次forkJoin任务都会拆分成两个子forkJoin任务进行，一直递归下去则会拆分成非常多的子任务
            ForkJoinDemo taks1 = new ForkJoinDemo(start,middle);
            taks1.fork(); //拆分任务，将任务压入线程队列
            ForkJoinDemo taks2 = new ForkJoinDemo(middle + 1,end);
            taks2.fork();
            return taks1.join() + taks2.join();
        }
    }
}
